import java.util.Deque;
import java.util.LinkedList;

/**
 * @author LKQ
 * @date 2021/12/30 18:57
 * @description 单调栈，栈内存储数组下标
 */
public class Solution3 {
    public static void main(String[] args) {
        int[] height = {4,2,0,3,2,5};
        Solution3 solution3 = new Solution3();
        solution3.trap(height);
    }
    public int trap(int[] height) {
        int ans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        int n = height.length;
        for (int i = 0; i < n; ++i) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                int top = stack.pop();
                if (stack.isEmpty()) {
                    break;
                }
                int left = stack.peek();
                int currWidth = i - left - 1;
                int currHeight = Math.min(height[left], height[i]) - height[top];
                ans += currWidth * currHeight;
            }
            stack.push(i);
        }
        return ans;
    }


}
